package common

import (
	"fmt"
	"log"

	"akexc.com/gin-template/util"
	"github.com/go-redis/redis"
)

var RedisClient *redis.Client

func InitRedis() {
	redisAddress := LoadRedis()
	client := redis.NewClient(&redis.Options{
		Addr: redisAddress,
		DB:   0, // use default DB
	})
	_, err := client.Ping().Result()
	if err != nil {
		fmt.Println(redisAddress)
		log.Fatalln("connect redis  failed, err:" + err.Error())
		RedisClient = nil
	} else {
		RedisClient = client
	}
}

func LoadRedis() string {
	cfg := util.GetIniCfg()
	host := cfg.Section("redis").Key("host").String()
	port := cfg.Section("redis").Key("port").String()
	return fmt.Sprintf("%s:%s", host, port)
}

func GetCache() *redis.Client {
	return RedisClient
}
